#用于统计账号家目录大小以及文件数。

import os,pymysql,datetime
import threading,random
import socket,re,time

def Num_name_Size(*args):
    print(args[0],)
    if not re.findall(args[1], args[0]):  # 判断传参开头是否符合要求
        print( "不符合要求不进行入库")
        return
    splicingdo_splice = Path #拼接路径
    # 账号所占磁盘情况
    Disk_size1 = os.popen("sudo du -sh " + splicingdo_splice).readline().split()[0]# 磁盘大小
    # Disk_size2 = re.split("/| ",os.popen("sudo du -sh " + path_username,args[0]))[3].strip() #获取账号名

    #获取当前日期
    today = str(datetime.date.today())
    #获取当前ip地址
    #res_ip = socket.gethostbyname(socket.gethostname())
    res_ip = os.popen('hostname -I').readline().strip()

    sum = 0
    for root,dirs,files in os.walk(splicingdo_splice):
        for h in files:
            sum += 1
    #切割获取用户名
    user_editcount = args[2]
    #账号状态L/LK 已禁用  P/PS未禁用
    user_Status = os.popen('sudo /usr/bin/passwd -S ' + args[2]).read().split()[1]
    #判断账号状态
    if user_Status in ['L','LK']:
        # （当前IP，用户名，状态（0禁用，1未禁用，2不存在），文件大小，文件数，当前日期）
        tuple_dict = (res_ip, user_editcount, 0, Disk_size1, sum, today, "账号已禁用")
        PyMysql(tuple_dict)
        print(tuple_dict)
    elif user_Status in ['P','PS']:
        #（当前IP，用户名，状态（0禁用，1未禁用，2不存在），文件大小，文件数，当前日期）
        tuple_dict = (res_ip,user_editcount,1,Disk_size1,sum,today,"账号未禁用")
        PyMysql(tuple_dict)
        print(tuple_dict)
    else: #状态不详输出状态
        tuple_dict = (res_ip, user_editcount, 1, Disk_size1, sum, today, user_Status)
        PyMysql(tuple_dict)





#pymysql开始插入数据
def PyMysql(*args):
    # 打开数据库连接
    db = pymysql.connect(host='w-bzrds-g4qk894976813f33d11.service.testdb',
            user='sftp_user',
            password='c(5ph5lJ1taKMy0#f',
            database='test',
            charset='utf8')

    #建表，没有此表创建表
    sql_create_table = '''
    CREATE TABLE if not exists `sftp_login_statistics` (
    `src_ip` varchar(20) NOT NULL,
    `name` varchar (25) DEFAULT NULL,
    `quantity` int(10) DEFAULT NULL,
    `desc` varchar (20) NOT NULL,
    `create_time` varchar NOT NULL,
    )'''

    with db.cursor() as cursor:
        sql = 'insert into sftp_username_status_statistics (' \
              '`sftp_src_address`,' \
              '`sftp_user`,' \
              '`sftp_user_status`,' \
              '`sftp_directory_size`,' \
              '`stftp_dire_file_num`,' \
              '`data_time`,' \
              '`annotation`) values (%s, %s, %s, %s,%s,%s,%s)'
        # params = ('10.11.118.41', 'sf_bz0423', 18, '10.11.54.21', '2022-10-15')
        # print(args[0])
        params = args[0] # for循环单个元组中取值再拼接未元组
        print(params)
        # 创建表
        #cursor.executemany(sql, params)
        cursor.execute(sql, params)
        db.commit()
        db.close()

def fount_user():
    pass


#获取账号家目录路径
def path_user():
    path_demo = []
    user_demo = []
    x = os.popen('cat /etc/passwd').readlines()
    for i in x:
        bate = re.split(":", i)[5]  # 账号路径
        User = re.split(":", i)[0]  # 用户名
        path_demo.append(bate)
        user_demo.append(User)
    return path_demo, user_demo




if(__name__=="__main__"):
    #定义指定入库的路径
    paths = '/service/SFTP/'
    path_path, user_name = path_user()
    for Path, UserName in zip(path_path, user_name):
        if os.path.exists(Path):  # 判断目录是否存在
            print(Path)
            RanDom = random.randint(1,15) #随机数用于执行线程号。
            #创建多线程实例
            thd1 = threading.Thread(target=Num_name_Size(Path,paths,UserName),args=("当前线程为{}".format,(RanDom)))
            thd1.start() #启动线程
            thd1.join() #等待线程结束 不然会一直挂起
        else:
            print("{}目录不存在".format(Path))
            # 获取当前日期
            today = str(datetime.date.today())
            # 获取当前ip地址
            res_ip = os.popen('hostname -I').readline().strip()
            # 切割获取用户名
            user_editcount = UserName
            fount_user = (res_ip,user_editcount,2,'0',0,today,"账号未查询到")
            PyMysql(fount_user)
